//
//  LoginViewController.m
//  WisdomZhuHai
//
//  Created by yewei on 14/10/30.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "Common.h"
#import "SSCheckBoxView.h"
#import "PersonPhoneLoginViewController.h"
#import "ThirdViewController.h"
#import "TransforController.h"
#import "MobClick.h"
#import "PasswordForgetViewController.h"
#import "PhoneVerifyViewController.h"

#define KEEP_PASSAWORD_LIST @"keepPassword.plst"
#define KEY_ACCOUNT @"key_account"
#define KEY_PASSWORD @"key_passord"
#define KEY_IFKEEPPASSWORD @"key_ifkeeppassord"
#define USER_INFO_LIST @"userinfo.text"
#define LOGINSTATUS @"loginStatus.plst"
@interface LoginViewController ()<loginSuccessWithPhoneDelegate, UIActionSheetDelegate>

@property (nonatomic,strong) IBOutlet UITextField *accountTextField;
@property (nonatomic,strong) IBOutlet UITextField *passwordTextField;
//@property (nonatomic,strong) IBOutlet UIView *keepPassWordView;
@property (nonatomic,strong) IBOutlet UIImageView *photoView;
//@property (nonatomic,strong) IBOutlet UIView *inputBackView;
//@property (nonatomic,strong) IBOutlet UIImageView *lineView1;
//@property (nonatomic,strong) IBOutlet UIImageView *lineView2;
@property (nonatomic,strong) IBOutlet UIButton *loginButton;
//@property (nonatomic,strong) SSCheckBoxView *checkBoxView;
@property (retain, nonatomic) IBOutlet UIImageView *img_top;


@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.img_top setFrame:CGRectMake(0, -45, 320, 140)];
    [self.view setFrame:CGRectMake(0, -45, 320, 568)];
    // Do any additional setup after loading the view from its nib.
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"sidebar/background.png"]];
//    self.inputBackView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"center/Bottom.png"]];
//    self.lineView1.image = [UIImage imageNamed:@"center/Division.png"];
//    self.lineView2.image = [UIImage imageNamed:@"center/Division.png"];
//    self.photoView.image = [UIImage imageNamed:@"center/Avatars_big.png"];
//    self.accountTextField.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"center/Avatars1.png"]];
//    self.accountTextField.leftViewMode = UITextFieldViewModeAlways;
//    self.passwordTextField.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"center/Cipher1.png"]];
//    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
//    [self.loginButton setBackgroundImage:[UIImage imageNamed:@"center/Options1.png"] forState:UIControlStateNormal];
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    
//    self.accountTextField.text = @"test";
//    self.checkBoxView = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(-6, -10, self.keepPassWordView.bounds.size.width, self.keepPassWordView.bounds.size.height) style:kSSCheckBoxViewStyleCustom checked:NO];  //SSCheckBoxView本身做了偏移
//    [self.checkBoxView setCheckedImage:@"center/Options3.png" uncheckedImage:@"center/Options4.png"];
//    [self.checkBoxView setChecked:NO];
//    [self.keepPassWordView addSubview:self.checkBoxView];
    
//    //检查是否记住密码
//    self.accountTextField.text = nil;
//    self.passwordTextField.text = nil;
//    NSString *filePath = [FileManager getFullDocumentPath:KEEP_PASSAWORD_LIST];
//    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
//    if(dic != nil)
//    {
//        self.accountTextField.text = [Common valueForKey:KEY_ACCOUNT dic:dic];
//        NSNumber *ifKeep = [Common valueForKey:KEY_IFKEEPPASSWORD dic:dic];
//        if([ifKeep boolValue])
//        {
//            [self.checkBoxView setChecked:YES];
//            self.passwordTextField.text = [Common valueForKey:KEY_PASSWORD dic:dic];
//        }
//    }
//    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewTapped:(UITapGestureRecognizer*)tapGr{
    NSLog(@"viewTapped");
    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}

-(IBAction)registerClick:(id)sender
{
    //注册事件
    RegisterViewController *registerCtl = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    registerCtl.loginDelegate = self;
    [self.navigationController pushViewController:registerCtl animated:YES];
}

-(IBAction)fastLoginAction:(id)sender{
    PersonPhoneLoginViewController *personPhoneLoginController = [[PersonPhoneLoginViewController alloc]init];
    NSLog(@"%s || action's actived.", __FUNCTION__);
    [personPhoneLoginController.view setFrame:self.view.frame];
    personPhoneLoginController.delegate = self;
    [self.navigationController pushViewController:personPhoneLoginController animated:YES];
}

- (IBAction)showActionSheet:(id)sender{
    [self gotoChangePassword2];
}

+(void)loginWithTarget:(id)target selector:(SEL)sel account:(NSString *)account passWord:(NSString *)passWord
{
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    //app版本
    NSString* versionNum =[infoDict objectForKey:@"CFBundleVersion"];
    //手机型号
    NSString* phoneModel = [[UIDevice currentDevice] model];
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    //物理地址
    //NSString* macAddr = [Common getMacAddr];
    NSString *phoneUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [[ProtocolManager shareInstance] login:account password:passWord mobileModel:phoneModel loginCity:@"" appVersion:versionNum OSversion:phoneVersion mac:phoneUUID target:target selector:sel];
}

-(IBAction)loginClick:(id)sender
{
    NSString *account = [self.accountTextField text];
    NSString *passWord = [self.passwordTextField text];
    NSString *alert = @"";
    if([account length] == 0)
    {
        alert = @"账户名不能为空！";
    }
    else if([passWord length] == 0)
    {
        alert = @"密码不能为空！";
    }
    if([alert length] != 0)
    {
        [[Common shareInstance] showAlertViewWithTitle:nil text:alert dismissTime:1.0];
        return;
    }
    
    [LoginViewController loginWithTarget:self selector:@selector(didFinishLogin:) account:account passWord:passWord];
    [[Common shareInstance] showLoadingViewWithMessage:nil];
}

-(void)didFinishLogin:(NSDictionary *)dic
{
    //NSLog(@"didFinishLogin %@",dic);
    [[Common shareInstance] stopLoadingView];
    if(dic == nil)
    {
        NSLog(@"%s || dic is nil", __FUNCTION__);
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"连接服务器错误" dismissTime:0.8];
        return;
    }else{
        if([dic objectForKey:@"Sex"] == nil || [dic objectForKey:@"Sex"] == NULL || [dic objectForKey:@"Sex"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Sex"];
        }
        if([dic objectForKey:@"Birthday"] == nil || [dic objectForKey:@"Birthday"] == NULL || [dic objectForKey:@"Birthday"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Birthday"];
        }
        if([dic objectForKey:@"Industry_to"] == nil || [dic objectForKey:@"Industry_to"] == NULL || [dic objectForKey:@"Industry_to"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Industry_to"];
        }
        if([dic objectForKey:@"Email"] == nil || [dic objectForKey:@"Email"] == NULL || [dic objectForKey:@"Email"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Email"];
        }
        if([dic objectForKey:@"Address"] == nil || [dic objectForKey:@"Address"] == NULL || [dic objectForKey:@"Address"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Address"];
        }
        if([[dic objectForKey:@"Birthday"] isEqualToString:@"0000-00-00"]){
            [dic setValue:@"1980-01-01" forKey:@"Birthday"];
        }
    }
    NSLog(@"========>>didFinishLogin-->>dic | %@",dic);
    NSUserDefaults *accountInfo = [NSUserDefaults standardUserDefaults];
    //[accountInfo setObject:[dic objectForKey:P_USERID] forKey:P_USERID];
    [accountInfo setObject: [dic objectForKey:@"Mobile"] forKey:@"Mobile"];
    [accountInfo setObject: [dic objectForKey:@"Username"] forKey:@"Username"];
    [accountInfo setObject:[dic objectForKey:@"Sex"] forKey:@"Sex"];
    [accountInfo setObject:[dic objectForKey:@"Birthday"] forKey:@"Birthday"];
    [accountInfo setObject:[dic objectForKey:@"Industry_to"] forKey:@"Industry_to"];
    [accountInfo setObject:[dic objectForKey:@"Email"] forKey:@"Email"];
    [accountInfo setObject:[dic objectForKey:@"Address"] forKey:@"Address"];
    [accountInfo synchronize];
    
    NSString *respCode = [Common valueForKey:P_RESPCODE dic:dic];
    if([respCode isEqualToString:CODE_HANDLE_SUCCESS])
    {
        [ProtocolManager shareInstance].sid = [Common valueForKey:P_SID dic:dic];
        if(![[dic objectForKey:@"loginType"]isEqualToString:@"0001"]){
            [ProtocolManager shareInstance].loginName = self.accountTextField.text;
            [ProtocolManager shareInstance].userId = [[dic objectForKey:@"userId"] integerValue];
        }else{
            [ProtocolManager shareInstance].loginName = [dic objectForKey:@"loginName"];
            [ProtocolManager shareInstance].userId = [[dic objectForKey:@"ID"] integerValue];
            [dic setValue:[dic objectForKey:@"ID"] forKey:P_USERID];
        }
        [self.delegate changeStatusAfterLogin:1];
        [ProtocolManager shareInstance].mobile = [dic objectForKey:@"Mobile"];
        [ProtocolManager shareInstance].currCash = [dic objectForKey:@"currCash"];
        [ProtocolManager shareInstance].isLoginedByPhone = NO;
        [[TransforController sharedInstanceOfPersonViewController] reloadData];
        NSMutableDictionary *savingDic = [NSMutableDictionary dictionary];
        //[savingDic setValue:[dic objectForKey:P_SID] forKey:P_SID];
        [savingDic setValue:[dic objectForKey:P_USERID] forKey:P_USERID];
        [savingDic setValue:[ProtocolManager shareInstance].loginName forKey:@"loginName"];
        [savingDic setValue:self.passwordTextField.text forKey:KEY_PASSWORD];
        [savingDic setValue:[dic objectForKey:@"Username"] forKey:@"Username"];
        [savingDic setValue:[dic objectForKey:P_MOBILENUMBER] forKey:P_MOBILENUMBER];
        [savingDic setValue:[dic objectForKey:@"Sex"] forKey:@"Sex"];
        [savingDic setValue:[dic objectForKey:@"Birthday"] forKey:@"Birthday"];
        [savingDic setValue:[dic objectForKey:@"Email"] forKey:@"Email"];
        [savingDic setValue:[dic objectForKey:@"Address"] forKey:@"Address"];
        [savingDic setValue:[dic objectForKey:@"Industry_to"] forKey:@"Industry_to"];
        [savingDic setValue:@"0001" forKey:@"LoginStatus"];
        [savingDic writeToFile:[FileManager getFullDocumentPath:LOGINSTATUS]atomically:YES];
//        NSString *filePath = [FileManager getFullDocumentPath:LOGINSTATUS];
//        NSDictionary *tempDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
//        NSLog(@"%s || dic:%@",__FUNCTION__, tempDic);
        //保存账户名密码
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:self.accountTextField.text forKey:KEY_ACCOUNT];
//        [dic setValue:[NSNumber numberWithBool:self.checkBoxView.checked] forKey:KEY_IFKEEPPASSWORD];
//        [dic setValue:@"" forKey:KEY_PASSWORD];
//        if(self.checkBoxView.checked)
//        {
//            [dic setValue:self.passwordTextField.text forKey:KEY_PASSWORD];
//        }
        [dic writeToFile:[FileManager getFullDocumentPath:KEEP_PASSAWORD_LIST] atomically:YES];
        //[dic writeToFile:[FileManager getFullDocumentPath:LOGINSTATUS]atomically:YES];
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"登陆成功" dismissTime:0.8];
        [TransforController umengEvent:@"UserLoginSuccess" attributes:@{@"loginname" : [ProtocolManager shareInstance].loginName} number:@(1) ct:@"900001"];
        [self.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES] afterDelay:0.8];
        //发送登陆成功的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFIY_LOGIN_SUCCESS object:nil userInfo:dic];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)gotoChangePassword2{
    UIActionSheet *actionSheetTest = [[UIActionSheet alloc]initWithTitle:@"修改密码的方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"通过邮箱找回",@"通过手机找回",nil];
    [actionSheetTest setTag:900002];
    [actionSheetTest dismissWithClickedButtonIndex:0 animated:YES];
    [actionSheetTest showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"%s || clickedButtonAtIndex:%d",__FUNCTION__, buttonIndex);
    if(buttonIndex == 0){
        PasswordForgetViewController *instance_passwordForget = [[PasswordForgetViewController alloc]init];
        instance_passwordForget.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:instance_passwordForget animated:YES];
    }else if(buttonIndex == 1){
        [self gotoChangePasswordWithPhone];
    }
}

- (void)gotoChangePasswordWithPhone{
    PhoneVerifyViewController *testViewController = [[PhoneVerifyViewController alloc]init];
    testViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:testViewController animated:YES];
}

-(void)setAccount:(NSString *)account{
    self.accountTextField.text = account;
}

- (void)viewDidUnload {
    [self setImg_top:nil];
    [super viewDidUnload];
}
@end
